// packageC/hotel/HotelIndex/HotelIndex.js
var location = require("../../../mybehaviors/location/location");
var app = getApp();
Page({
  behaviors: [location],
  /**
	 * 页面的初始数据
	 */
  data: {
    language: '',
    show1: false,
    show2: false,
    show3: false,
    value: 0,
    valueData: 0,
    date_obj_arr: [],
    //入住时间
    start_time: "",
    //离店时间
    end_time: "",
    //入住几晚
    night_day: "",
    //轮播图片
    carousels_arr: [],
    //banner图片
    bannerObj: {},
    //分类
    catagory_arr: [],
    //定位
    location: {},
    //酒店列表
    hotel_arr: [],
    loading: false,
    allLoaded: false,
    goload: true,
    isLoadMore: true,
    page: 1,
    total_page: 0,
    star_arr: [{
      name: "二星及以下/经济型",
      value: 2
    },
    {
      name: "三星/舒适",
      value: 3
    },
    {
      name: "四星/高档",
      value: 4
    },
    {
      name: "五星/豪华",
      value: 5
    },
    {
      name: "六星",
      value: 6
    },
    {
      name: "七星",
      value: 7
    },
    {
      name: "八星",
      value: 8
    },
    {
      name: "不限",
      value: 0
    }
    ],
    current_index: 0,
    star_value: 0,
    toolbar: false,
    PageNameList: {}, //标题
    address: "",
    point: {
      lat: '',
      lng: ''
    },
    city: '',
    title: '',
    HOTEL_LIST: "plugin.hotel.frontend.hotel.hotel.get-hotel-list-to-page",
    INDEX_OTHER_URL: "plugin.hotel.frontend.hotel.get-default.get-index-data",
    CATAGORY_URL: "plugin.hotel.frontend.hotel.hotel-category.get-list"
  },

  /**
	 * 生命周期函数--监听页面加载
	 */
  onLoad: function(options) {
    this.getInitTime();
    this.getOtherData();
    this.getCatagoryData();
    this.getCustomizeHotelHead();
    if (options.addressData) {
      let addressData = JSON.parse(options.addressData);
      this.setData({
        'point.lat': addressData.latitude,
        'point.lng': addressData.longitude,
        address: addressData.title,
        title: addressData.title,
        city: addressData.city
      });
      this.getList();
    } else {
      this._getLocation(() => {this.getList();});
    }

  },

  /**
	 * 生命周期函数--监听页面初次渲染完成
	 */
  onReady: function() {
    let language = wx.getStorageSync('langIndex');
    this.setData({ 'language': language.en});
  },

  /**
	 * 生命周期函数--监听页面显示
	 */
  onShow: function() {

  },

  /**
	 * 生命周期函数--监听页面隐藏
	 */
  onHide: function() {

  },

  /**
	 * 生命周期函数--监听页面卸载
	 */
  onUnload: function() {

  },

  /**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
  onPullDownRefresh: function() {

  },

  /**
	 * 页面上拉触底事件的处理函数
	 */
  onReachBottom: function() {
    if (this.data.isLoadMore) {
      this.getMoreList();
    } else {
      console.log('没有更多数据');
    }
  },

  /**
	 * 用户点击右上角分享
	 */
  onShareAppMessage: function() {

  },
  show2btn() {
    this.setData({
      show2: true
    });
  },
  show3btn() {
    this.setData({
      show3: true
    });
  },
  show1btn() {
    this.setData({
      show1: true
    });
  },
  getList() {
    var that = this;
    let urlStr = app.getNetAddresss(that.data.HOTEL_LIST);
    urlStr += '&lng=' + this.data.point.lng;
    urlStr += '&lat=' + this.data.point.lat;
    urlStr += '&city_name=' + this.data.city;
    urlStr += '&page=' + this.data.page;
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            hotel_arr: res.data.data,
            hotel_total_page: res.data.last_page
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  getInitTime() {
    let now = new Date();
    let next = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    this.setData({
      start_time: `${now.getFullYear()}/${
        now.getMonth() + 1 < 10
          ? `0${now.getMonth() + 1}`
          : `${now.getMonth() + 1}`
      }/${now.getDate() < 10 ? `0${now.getDate()}` : `${now.getDate()}`}`
    });
    this.setData({
      end_time: `${next.getFullYear()}/${
        next.getMonth() + 1 < 10
          ? `0${next.getMonth() + 1}`
          : `${next.getMonth() + 1}`
      }/${next.getDate() < 10 ? `0${next.getDate()}` : `${next.getDate()}`}`
    });
  },
  //获取轮播 分类数据
  getOtherData() {
    var that = this;
    let urlStr = app.getNetAddresss(that.data.INDEX_OTHER_URL);
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            carousels_arr: res.data.carousels,
            bannerObj: res.data.banner
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //获取分类
  getCatagoryData() {
    var that = this;
    let urlStr = app.getNetAddresss(that.data.CATAGORY_URL);
    app._getNetWork({
      url: urlStr,
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            catagory_arr: res.data
          });
        }
      },
      fail: function(res) {
        console.log(res);
      }
    });
  },
  //获取酒店自定义字段
  getCustomizeHotelHead() {
    let that = this;
    let isQuestHotel = "";
    try {
      const value = wx.getStorageSync('customizeHotelHead');
      if (value) {
        isQuestHotel = value;
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
    if (!app._isTextEmpty(isQuestHotel)) {
      this.setData({
        PageNameList: JSON.parse(isQuestHotel)
      });
      wx.setNavigationBarTitle({
        title: this.data.PageNameList.hotel_first_page
      });
    } else {
      let urlStr = app.getNetAddresss("plugin.hotel.frontend.hotel.get-hotel-info.get-custom-name");
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              PageNameList: res.data
            });
            wx.setNavigationBarTitle({
              title: res.data.hotel_first_page ? res.data.hotel_first_page : ''
            });
            try {
              wx.setStorageSync('customizeHotelHead', JSON.stringify(res.data));
            } catch (e) {
              console.log(e);
            }
          }
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  //图片跳转
  imgHref(e) {
    let url = e.currentTarget.dataset.link;
    try {
      wx.navigateTo({
        url: url
      });
    } catch (e) {
      wx.showToast({
        title: '链接设置错误',
        icon: 'none',
        duration: 2000
      });
      //TODO handle the exception
    }
  },
  //路由跳转
  routerGo(e) {
    // let value = e.currentTarget.dataset.mum;
    wx.navigateTo({
      url: '/packageC/o2o/o2oLocation/o2oLocation?tag=hotel'
    });
  },
  //搜索
  gotoSearch() {
    wx.navigateTo({
      url: '/packageC/hotel/HotelSearch/HotelSearch?start=' + this.data.start_time + '&end=' + this.data.end_time
    });
  },
  //搜索2
  gotoSearch2() {
    if (app._isTextEmpty(this.data.start_time)) {
      wx.showToast({
        title: '请选择入住时间',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    if (app._isTextEmpty(this.data.end_time)) {
      wx.showToast({
        title: '请选择离店时间',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.navigateTo({
      url: '/packageC/hotel/HotelSearch/HotelSearch?start=' + this.data.start_time + '&end=' + this.data.end_time +
				'&price=' + this.data.value + '&star=' + this.data.star_value
    });
  },
  acceptTime(e) {
    let type = e.detail.type;
    let date = e.detail.date;
    if (type == "离店") {
      this.setData({
        end_time: date
      });
    } else if (type == "入住") {
      this.setData({
        start_time: date
      });
    }
    this.checkDate(type);
  },
  checkDate(type) {
    //入住日期不能为空
    //离店日期不能小于住店日期
    //离店日期不能和住店日期同一天
    let start = new Date(this.data.start_time).getTime();
    let end = new Date(this.data.end_time).getTime();
    if (app._isTextEmpty(this.data.start_time)) {
      wx.showToast({
        title: '请先选择入住日期',
        icon: 'none',
        duration: 2000
      });
      this.setData({
        end_time: ""
      });
      return;
    } else {
      if (start == end) {
        wx.showToast({
          title: '入住和离店日期不能为同一天',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          end_time: ""
        });
        return;
      }
      if (start > end) {
        wx.showToast({
          title: '离店日期需要大于入店日期',
          icon: 'none',
          duration: 2000
        });
        this.setData({
          end_time: ""
        });
        return;
      }
      //关闭弹窗
      if (type == "离店") {
        //计算多少晚
        this.getDays(this.data.start_time, this.data.end_time);
        this.setData({
          show3: false
        });
      } else if (type == "入住") {
        this.setData({
          show2: false
        });
      }
    }
  },
  closeHander(e) {
    let type = e.detail;
    if (type == "离店") {
      this.setData({
        show3: false
      });
    } else if (type == "入住") {
      this.setData({
        show2: false
      });
    }
  },
  //时间日期
  getDays(strDateStart, strDateEnd) {
    let strSeparator = "-"; //日期分隔符
    let oDate1, oDate2, iDays;
    oDate1 = strDateStart.split(strSeparator);
    oDate2 = strDateEnd.split(strSeparator);
    let strDateS = new Date(oDate1[0], oDate1[1] - 1, oDate1[2]);
    let strDateE = new Date(oDate2[0], oDate2[1] - 1, oDate2[2]);
    iDays = parseInt(Math.abs(strDateS - strDateE) / 1000 / 60 / 60 / 24); //把相差的毫秒数转换为天数
    console.log(iDays);
    this.setData({
      night_day: iDays
    });
  },
  slidedrag(e) {
    let num = e.detail.value;
    let num_1 = num * 10;
    this.setData({
      value: num_1
    });
  },
  slideChange(e) {
    let num = e.detail;
    let num_1 = num * 10;
    this.setData({
      value: num_1
    });
  },
  starChoose(e) {
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    this.setData({
      current_index: index,
      star_value: item.value
    });
  },
  starSubmit(e) {
    let tag = e.currentTarget.dataset.val;
    if (tag == "reset") {
      this.setData({
        current_index: 0,
        star_value: 2,
        value: 0,
        valueData: 0
      });
    } else if (tag == "complete") {
      this.setData({
        show1: false
      });
    }
  },
  show1closebtn() {
    this.setData({
      show1: false
    });
  },
  show2closebtn() {
    this.setData({
      show2: false
    });
  },
  show3closebtn() {
    this.setData({
      show3: false
    });
  },
  //分类跳转
  goCatagory(e) {
    let value = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/packageC/hotel/HotelSearch/HotelSearch?category=' + value.id
    });
  },
  getMoreList() {
    var that = this;
    if (this.data.page == this.data.total_page) {
      return;
    }
    if (this.data.page >= this.data.total_page) {
      that.setData({
        loading: true,
        allLoaded: true
      });
      return;
    } else {
      this.setData({
        page: this.data.page + 1
      });
      let urlStr = app.getNetAddresss(that.data.HOTEL_LIST);
      urlStr += '&lng=' + this.data.point.lng;
      urlStr += '&lat=' + this.data.point.lat;
      urlStr += '&city_name=' + this.data.city;
      urlStr += '&page=' + this.data.page;
      app._getNetWork({
        url: urlStr,
        success: function(resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              loading: false,
              allLoaded: false,
              hotel_arr: that.data.hotel_arr.concat(res.data.data)
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              loading: true,
              allLoaded: true,
              isLoadMore: false
            });
            return;
          }

        },
        fail: function(res) {
          console.log(res);
        }
      });
    }
  },
  gohome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  goorderlist() {
    wx.navigateTo({
      url: '/packageA/member/myOrder_v2/myOrder_v2?status=0&orderType=hotel'
    });
  },
  gomember() {
    wx.reLaunch({
      url: '/packageG/member_v2/member_v2'
    });
  },
  showToolbar() {
    this.setData({
      toolbar: !this.data.toolbar
    });
  },
});
